package com.hison.tandainbao.util;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @ClassName: LoginInterceptor
 * @Descripiton: 登录拦截 拦截器
 * @Author: 小郑
 * @Date： 2023/5/26 16:39
 * @Version：1.8
 **/
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 前置拦截
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //判断是否需要拦截（判断ThreadLocal中是否有用户）
        if(UserHolder.getUser() == null){
            //没有，需要拦截
            response.setStatus(401);
            PrintWriter writer = response.getWriter();
            writer.print("用户未登录");

            return false;
        }
        //有用户则，放行
        return true;
    }


}